<?php

namespace app\common\model;

use think\Cache;

/**
 * 幸运星提问回答 模型类
 * Class DivinationTips
 * @package app\common\model
 */
class LuckyQuestionAnswer extends Base
{

    /**
     * 用户 所有的幸运星提问&回复 ids（+uid）
     */
    const REDIS_KEY_IDS = 'lucky_qa_ids_';
    /**
     * 幸运星提问&回复详情（+id）
     */
    const REDIS_KEY_DETAIL = 'lucky_qa_detail_';

    protected $table = 'wechat_backup_07_18_14_43_00.app_question_answer';// 定义表名

    /**
     * 获取详情
     * @param array $all_list
     * @return array|bool|false|mixed|\PDOStatement|string|\think\Model
     */
    public function getDetails($all_list = [])
    {
        $result = [];
        $ids = $this->getAllNotCachedIds($all_list, self::REDIS_KEY_DETAIL);
        try
        {
            if (strlen($ids) > 0)
            {
                $where = 'id in(' . $ids . ')';
                $result = $this
                    ->field('id,lid,question,answer,create_time question_time,answer_time')
                    ->where($where)
                    ->order('id DESC')
                    ->select();
                $result = json_decode(json_encode($result, true), true);
                if ($this->cache_on >= 1)
                    foreach ($result as $v)
                        Cache::set(self::REDIS_KEY_DETAIL . $v['id'], $v, $this->cache_time);
            }
            if ($this->cache_on >= 1)//如果缓存打开，循环获取，因为缓存里已经有了数据
            {
                $result = [];
                foreach ($all_list as $v)
                    $result[] = Cache::get(self::REDIS_KEY_DETAIL . $v['id']);
            }
        }
        catch (\Exception $e)
        {
            // 错误信息写入日志
            \think\Log::write('幸运星提问回答错误:' . '[' . $ids . ']', 'error', true);
        }

        return $result;
    }

    /**
     * 获取用户 所有的幸运星提问回答列表
     * @param $uid
     * @return array|bool|false|mixed|\PDOStatement|string|\think\Model
     */
    public function getList($uid)
    {
        $lucky_qa_ids = false;
        if ($this->cache_on >= 1)
        {
            $lucky_qa_ids = Cache::get(self::REDIS_KEY_IDS . $uid);
        }
        if ($lucky_qa_ids === false)
        {
            try
            {
                $lucky_qa_ids = $this
                    ->field('id')
                    ->where('uid', $uid)
                    ->order('id DESC')
                    ->select();
            }
            catch (\Exception $e)
            {
                // 错误信息写入日志
                \think\Log::write('获取用户 所有的幸运星提问回答列表:' . '[' . $uid . ']', 'error', true);
            }
            //获取数据
            $lucky_qa_ids = json_decode(json_encode($lucky_qa_ids, true), true);

            //存储所有ids
            if ($this->cache_on >= 1)
            {
                Cache::set(self::REDIS_KEY_IDS . $uid, $lucky_qa_ids, $this->cache_time);
            }
        }
        $data_list = $this->getDetails($lucky_qa_ids);
        return $data_list;
    }
}
